<template>
  <view class="add-order">
    <up-toast ref="uToast" />
    <image class="bg-logo" src="@/static/image/logo_bg.png" />
    <view class="topbar" :style="topbarStyle">
      <view class="topbar-returnBtn" @click="handleReturnPage">
        <up-icon name="arrow-left" color="white" size="24"></up-icon>
        <text class="topbar-returnBtn-text">返回</text>
      </view>
      <view class="topbar-title">{{ openType === 'add' ? '车检预约' : '修改预约' }}</view>
    </view>
    <view class="main" :style="mainStyle">
      <view class="main-form">
        <up-form ref="formRef" labelWidth="120" :model="formData" :rules="formRules" errorType="toast">
          <view class="main-form-item">
            <view class="main-form-item-title"><text class="main-form-item-title-important">基本</text>信息</view>
            <up-form-item label="车牌号" prop="licensePlate" :borderBottom="false" :leftIcon="leftIconDisabled" :leftIconStyle="leftIconDisabledStyle">
              <template #right>
                <view @click.stop="handleOpenlicensePlatePopup">
                  <up-input v-model="formData.licensePlate" readonly inputAlign="right" placeholder="请输入车牌号" border="none" />
                </view>
                <!-- <ycy-license-plate-popup ref="licensePlatePopupRef" v-model:value="formData.licensePlate" /> -->
              </template>
            </up-form-item>
            <up-form-item label="联系人姓名" prop="userName" :borderBottom="false" :leftIcon="leftIconEdit" :leftIconStyle="leftIconEditStyle">
              <template #right>
                <up-input v-model="formData.userName" inputAlign="right" border="none" placeholder="请输入联系人姓名" />
              </template>
            </up-form-item>
            <up-form-item label="联系人电话" prop="userPhone" required :borderBottom="false" :leftIcon="leftIconEdit" :leftIconStyle="leftIconEditStyle">
              <template #right>
                <up-input v-model="formData.userPhone" inputAlign="right" border="none" placeholder="请输入" />
              </template>
            </up-form-item>
            <up-form-item label="留言" prop="desc" :borderBottom="false" :leftIcon="leftIconEdit" :leftIconStyle="leftIconEditStyle">
              <template #right>
                <up-input v-model="formData.desc" inputAlign="right" border="none" placeholder="请填写" />
              </template>
            </up-form-item>
          </view>
          <view class="main-form-item">
            <view class="main-form-item-title"><text class="main-form-item-title-important">订单</text>信息</view>
            <up-form-item label="监测站名称" prop="checkStation" :borderBottom="false" :leftIcon="leftIconDisabled" :leftIconStyle="leftIconDisabledStyle">
              <template #right>
                <up-input v-model="formData.checkStation" readonly inputAlign="right" border="none" />
              </template>
            </up-form-item>
            <up-form-item label="订单类型" prop="orderType" :borderBottom="false" :leftIcon="leftIconDisabled" :leftIconStyle="leftIconDisabledStyle">
              <template #right>
                <up-input v-model="formData.orderType" inputAlign="right" readonly border="none" />
              </template>
            </up-form-item>
            <up-form-item label="预约时间" prop="checkTime" required :borderBottom="false" :leftIcon="leftIconDisabled" :leftIconStyle="leftIconDisabledStyle">
              <ycy-datetime-picker v-model:value="formData.checkTime" mode="datetime" :readonly="openType === 'edit'" title="预约时间" placeholder="请选择预约时间" />
            </up-form-item>
          </view>
        </up-form>
      </view>
    </view>
    <view class="bottom-bar">
      <text class="bottom-bar-price"><text class="bottom-bar-price-prefix">￥</text>{{ formData.price }}</text>
      <button class="bottom-bar-btn" @click="handleSubmit">{{ openType === 'add' ? '立即下单' : '确认修改' }}</button>
    </view>
    <!-- 确认下单弹窗 -->
    <up-modal
			ref="uModal"
      :show="isShowConfirmModel"
      @confirm="handleConfirm"
      @cancel="handleCancel"
      @close="handleClose"
			:title="openType === 'add' ? '是否确认下单?' : '是否确认修改?'"
			confirmColor="#125796"
			showCancelButton
			asyncClose
      closeOnClickOverlay />
  </view>
</template>

<script setup>
  import { ref, reactive, computed, watchEffect, watch } from 'vue';
  import { onLoad, onShow } from '@dcloudio/uni-app';
  import API from '@/api';
  import useCommonUtils from '@/utils/common'

  const { formatDate, getRandomDayInPastMonth } = useCommonUtils();
  onLoad(async options => {
    // options.carId = '0';
    // options.checkStation = '中渝检测';
    // options.checkPrice = '230';
    if (options.orderId) {
      openType.value = 'edit'
      await getOrderDetail(options.orderId);
    }else if (options.carId && options.stationData) {
      openType.value = 'add'
      const stationData = JSON.parse(options.stationData);
      Object.assign(formData, stationData)
      // formData.checkStation = stationData.checkStation;
      // formData.checkStationLocation = stationData.checkStationLocation;
      // formData.price = stationData.checkPrice;
      await getCarDetail(options.carId);
    } else uni.navigateBack();
  });

  const { globalData } = getApp();
  const leftIconEditStyle = ref('color: #1e7eba; fontSize: 24px');
  const leftIconDisabledStyle = ref('color: #57c244; fontSize: 22px');
  const leftIconEdit = computed(() => openType.value === 'edit' ? 'edit-pen-fill' : '')
  const leftIconDisabled = computed(() => openType.value === 'edit' ? 'checkmark-circle-fill' : '')
  const topbarStyle = `height: ${globalData.navBarHeight}px; margin-top: ${globalData.statusBarHeight}px`;
  const mainStyle = `margin-top: ${globalData.navBarHeight + globalData.statusBarHeight + 12}px`;
  const openType = ref('add');
	// const submitData = ref({})
  let submitData = {}
  // const licensePlatePopupRef = ref(null);
  const formRef = ref(null);
	const isShowConfirmModel = ref(false)
  const carInfo = reactive({});
  const formData = reactive({
    id: '',
    licensePlate: '',
    checkStation: '',
    orderType: '',
    userName: '',
    userPhone: '',
    checkTime: '',
    desc: ''
  });

  const formRules = reactive({
    licensePlate: [{ type: 'string', required: true, message: '请输入车牌号', trigger: ['blur'] }],
    checkTime: [{ type: 'string', required: true, message: '请选择预约时间', trigger: ['blur'] }],
    userName: [{ type: 'string', required: true, message: '请输入联系人姓名', trigger: ['blur'] }],
    userPhone: [{ type: 'string', required: true, message: '请输入联系人电话', trigger: ['blur'] }]
  });

  const handleOpenlicensePlatePopup = () => {
    // licensePlatePopupRef.value.open(formData.licensePlate);
  };

  // const mockData = {
	// 	  checkStation: "中渝检测", //1
  //     checkStationLocation: '重庆市渝中区', //1
	// 	  checkTime: "2024-06-06", //1
	// 	  desc: "车辆贴了膜", // 1
	// 	  id: "D1717659794981", //1
	// 	  licensePlate: "渝ARG681",
	// 	  orderType: "燃油车检测", //1
	// 	  userName: "张三", //1
	// 	  userPhone: "123", //1
  //     price: '240', //1
  //     createTime: "2024-06-06", //1
  //     payType: '微信支付', //1
	// 	  status: 1, //待付款0、待使用1、已完成2、已退款3、已取消4 //1
  //     code: '9903 3499 4986 30', //1
	// 	  qrCodeUrl: 'https://tse3-mm.cn.bing.net/th/id/OIP-C.ZDgcgVP7i2iZlJERZwyeuQHaHa?w=212&h=212&c=7&r=0&o=5&pid=1.7' //1
	//   }

  const handleSubmit = () => {
    submitData = { ...formData };
    formRef.value
      .validate()
      .then(async valid => {
        if (!valid) return;
				// submitData.value = submitData
        // submitData.finishTime = formatDate(getRandomDayInPastMonth(carInfo.lastCheckTime, 3), 'datetime')
        submitData.payType = '微信支付';
        submitData.code = '9903 3499 4986 30';
        submitData.qrCodeUrl = 'https://tse3-mm.cn.bing.net/th/id/OIP-C.ZDgcgVP7i2iZlJERZwyeuQHaHa?w=212&h=212&c=7&r=0&o=5&pid=1.7'
        console.log('校验通过 submitData', submitData);
				isShowConfirmModel.value = true
      })
      .catch(e => {});
  };
	
	const handleConfirm = async () => {
    console.log('handleConfirm', submitData);
    let res = {}
    if (submitData.id) {
      res = await API.order.update(submitData)
      uni.$u.toast('修改成功');
    } else {
      submitData.status = 1; //待付款0、待使用1、已完成2、已取消3、已退款4
      submitData.payTime = formatDate(new Date(), 'datetime')
      res = await API.order.add(submitData)
      uni.$u.toast('预约成功');
    }
		uni.redirectTo({
		  url: `/pages/mine/pages/order/orderResult?orderId=${res.data.id}`
		});
		handleClose()
	}
	
	const handleCancel = async () => {
    if (submitData.id) {
      handleClose()
      return;
    }
    submitData.status = 0; //待付款0、待使用1、已完成2、已取消3、已退款4
    const res = await API.order.add(submitData)
    uni.$u.toast('预约已存入待付款中');
    uni.redirectTo({
		  url: `/pages/mine/pages/order/orderResult?orderId=${res.data.id}`
		});
    handleClose()
	}
	
	const handleClose = () => {
		isShowConfirmModel.value = false
	}

  const handleReturnPage = () => {
    uni.navigateBack();
  };

  const getCarDetail = async carId => {
    const res = await API.car.detail(carId);
    Object.assign(carInfo, res.data);
    console.log('getCarDetail', carInfo);
    formData.licensePlate = carInfo.licensePlate;
    formData.userName = carInfo.owner;
    formData.orderType = carInfo.licensePlate.length === 7 ? '燃油车检测' : '新能源车检测';
  };

  const getOrderDetail =  async orderId => {
    // const mockData = {
    //   carId: '0',
    //   checkStation: '中渝检测',
    //   checkPrice: '230',
    //   licensePlate: '川A12345',
    //   userName: '张三',
    //   userPhone: '13800000000',
    //   checkTime: '2022-01-01 10:00',
    //   desc: '备注信息',
    //   orderType: '燃油车检测'
    // }
    // Object.assign(formData, mockData);

    const res = await API.order.detail(orderId)
	  Object.assign(formData, res.data)
  }
</script>

<style lang="scss" scoped>
  .add-order {
    height: 100vh;
    overflow: auto;
    position: relative;
    background: linear-gradient(to bottom, #0055a5 0, #f7f7f7 520rpx);

    .bg-logo {
      position: fixed;
      top: -3%;
      width: 680rpx;
      height: 600rpx;
      right: 0;
      pointer-events: none;
    }

    .topbar {
      color: white;
      z-index: 1;
      position: absolute;
      width: 100%;
      box-sizing: border-box;
      padding: 0 12px;
      @include flex-row(flex-start, center);

      &-returnBtn {
        @include flex-row(flex-start, center);

        &-text {
          margin-left: 4px;
          font-size: 14px;
        }
      }

      &-title {
        position: absolute;
        left: 50%;
        transform: translateX(-50%);
      }
    }

    .main {
      margin-bottom: calc(46px + 20px + 12px);

      &-car-card {
        margin: 12px;
        margin-bottom: 0;
      }

      &-form {
        // @include card;
        // padding: 12px;

        &-item {
          @include card;
          padding: 12px;
          &-title {
            font-size: 15px;
            display: flex;
            align-items: center;
            height: 20px;
            font-weight: bold;
            color: $uni-text-color;
            margin-bottom: 12px;

            &-important {
              color: $uni-color-primary;
            }

            &::before {
              content: '';
              margin-right: 6px;
              width: 4px;
              height: 100%;
              border-radius: 2px;
              background: $uni-color-gradient-blue;
            }
          }
        }
      }
    }

    .bottom-bar {
      z-index: 9;
      position: fixed;
      bottom: 0;
      width: 100%;
      background-color: $uni-bg-color-grey;
      padding: 12px;
      padding-bottom: 18px;
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;

      &-price {
        font-size: 24px;
        color: $uni-color-primary;
        font-weight: bold;

        &-prefix {
          font-size: 16px;
        }
      }

      &-btn {
        flex: 1;
        margin-left: 12px;
        height: 45px;
        line-height: 45px;
        border-radius: 12px;
        box-shadow: 0px 4px 5px 0px rgba(0, 0, 0, 0.02);
        text-align: center;
        color: white;
        font-weight: lighter;
        letter-spacing: 2px;
        background: linear-gradient(145deg, #1e7eba, #0558a8);
      }
    }
  }
</style>
